//
//  QDDisSubDivideVC.m
//  QuickDoctor
//
//  Created by 李伟 on 2016/12/22.
//  Copyright © 2016年 Eric. All rights reserved.
//

#import "QDDisSubDivideVC.h"
#import "NetworkData.h"
#import "PinYin4Objc.h"
#import "QDDiseaseDetailVC.h"

static NSString *flag = @"cellFlag";
@interface QDDisSubDivideVC ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchResultsUpdating>
//原数据数组
@property (nonatomic, strong) NSMutableArray *dataArray;

//搜索数据数组
@property (nonatomic, strong) NSMutableArray *searchingArray;

//tb
@property (nonatomic, weak) UITableView *tableView;

//搜索
@property (nonatomic, strong) UISearchController *searchController;

@end

@implementation QDDisSubDivideVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadData];
    
    [self setupUI];

}
#pragma mark
#pragma mark - 懒加载数组
-(NSMutableArray *)searchingArray
{
    if (!_searchingArray) {
        _searchingArray = [NSMutableArray array];
    }
    return _searchingArray;
}

#pragma mark
#pragma mark - 获取原数据
- (void)loadData
{
    //工具类
    NetworkData *workData = [NetworkData sharedNetworkData];
    
    [workData getCIListDataWith:self.ci1_id pageNumber:@1 completeBlock:^(id responseObject, NSError *error) {
        //数据数组
        NSMutableArray *mArray = [NSMutableArray array];

        NSArray *array = responseObject[@"data"];
        for (NSDictionary *dict in array) {
            
            [mArray addObject: dict[@"ci3_name"]];
        }
        self.dataArray = mArray.copy;
    }];
}
#pragma mark
#pragma mark - 获取搜索数据
- (void)getSearchArray:(NSString *)searchText
{
    NSString *searchingStr = searchText;
    if (searchingStr.length > 0) {
        
        for (NSString *tempStr in _dataArray) {
            //汉字
            NSRange searchResult = [tempStr rangeOfString:searchText options:NSCaseInsensitiveSearch];
           
            //拼音
            NSString *tempStrPY = [self chineseToPinyin:tempStr];
            NSRange searchResultPY = [tempStrPY rangeOfString:searchText options:NSCaseInsensitiveSearch];
            
            //首字母
            //取出单字的拼音
            NSArray<NSString*> *pinYinS = [tempStrPY componentsSeparatedByString:@" "];
            //拼接首字母
            __block NSString *preLetters = [NSString string];
            [pinYinS enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                //取出首字母
                NSString *preLetter = [pinYinS[idx] substringToIndex:1];
                //拼接
                preLetters = [preLetters stringByAppendingString:preLetter];
            }];
            
            NSRange searchResultPre = [preLetters rangeOfString:searchText options:NSCaseInsensitiveSearch];
            
            if (searchResult.length > 0 || searchResultPY.length > 0 || searchResultPre.length > 0) {
                [self.searchingArray addObject:tempStr];
            }
        }
    }
}

#pragma mark
#pragma mark - 中文转拼音方法
- (NSString * )chineseToPinyin:(NSString*)inputText
{
    HanyuPinyinOutputFormat * outputF = [[HanyuPinyinOutputFormat alloc]init];
    [outputF setToneType:ToneTypeWithoutTone];
    
    [outputF setVCharType:VCharTypeWithV];
    
    [outputF setCaseType:CaseTypeLowercase];
    
    NSString *result = [PinyinHelper toHanyuPinyinStringWithNSString:inputText withHanyuPinyinOutputFormat:outputF withNSString:@" "];
    
    return result;
}

#pragma mark
#pragma mark - 获取搜索数据,重新布局
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *searchString = [self.searchController.searchBar text];
    //当搜索数组中有值时,清空
    if (_searchingArray.count > 0) {
        [self.searchingArray removeAllObjects];
    }
    //获取搜索数组
    [self getSearchArray:searchString];
    
    //刷新表格
    [self.tableView reloadData];
}


#pragma mark
#pragma mark - 重写原数据set,重新布局
- (void)setDataArray:(NSMutableArray *)dataArray
{
    _dataArray = dataArray;
    
    [self.tableView reloadData];
}

#pragma mark
#pragma mark - 搭建界面
- (void)setupUI
{
    #pragma mark -- tableView
    UITableView *tableView = [[UITableView alloc]init];
    _tableView = tableView;
    [self.view addSubview:tableView];
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    tableView.delegate = self;
    tableView.dataSource = self;
    
    #pragma mark -- 搜索框
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    
    //搜索是否隐藏背景视图
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //搜索是否隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = YES;
    
    self.searchController.searchBar.placeholder = @"输入想要搜索的疾病";

    
    //将tb的表头设置为搜索框
    self.tableView.tableHeaderView = self.searchController.searchBar;
    [self.searchController loadViewIfNeeded];
}


#pragma mark
#pragma mark - 数据源方法
#pragma mark -- 设置区域的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchController.active) {
        return [self.searchingArray count];
    }else{
        return [self.dataArray count];
    }
}
#pragma mark -- 返回单元格内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:flag];
   
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flag];
    }
    
    //根据数据源更改cell
    if (self.searchController.active) {
        [cell.textLabel setText:self.searchingArray[indexPath.row]];
    }
    else{
        [cell.textLabel setText:self.dataArray[indexPath.row]];
    }
    return cell;
}

#pragma mark
#pragma mark - 选中cell,返回上级页面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if (_backBlock) {
        _backBlock(cell.textLabel.text);
    }
    //移除搜索框
    [self.searchController dismissViewControllerAnimated:NO completion:nil];
    
    [self.navigationController popViewControllerAnimated:YES];
}

@end
